import type { ProColumns } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { message } from 'antd';
import { EditableProTable, ProCard, ProFormField, ProFormRadio } from '@ant-design/pro-components';
import React, { useState } from 'react';
import request from '@/services/request';
import { addUser, editUser, deleteUser, selectUser } from './services'; 

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

type DataSourceType = {
  user_id: React.Key;
  username: string;
  roleId: number;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: string;
  update_at?: string;
  children?: DataSourceType[];
};

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [position, setPosition] = useState<'top' | 'bottom' | 'hidden'>('bottom');

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '用户名',
      key: 'username',
      dataIndex: 'username',
      tooltip: '只读，使用form.getFieldValue获取不到值',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
        };
      },
      // 第一行不允许编辑
      // editable: false,
      width: '15%',
    },
    {
      title: '权限',
      key: 'role_id',
      dataIndex: 'role_id',
      valueType: 'select',
      valueEnum: {
        1: {
          text: '管理员',
        },
        2: {
          text: '普通用户',
        },
      },
      // render: (_) => <a>{_ === 1 ? '管理员' : '普通用户'}</a>
    },
    {
      title: '描述',
      dataIndex: 'decs',
      render: () => <a>127成员</a>
    },
    {
      title: '活动时间',
      dataIndex: 'created_at',
      valueType: 'date',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.user_id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={async () => {
            console.log(record.user_id);
            const body = {
              code: 1,
              msg: 'delete',
              data: {
                user_id: record.user_id,
              }
            }
            const { msg } = await deleteUser(body);
            if (msg === 'success') {
              message.success(msg);
              setDataSource(dataSource.filter((item) => item.user_id !== record.user_id));
            } else {
              message.error(msg);
            }
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const params = {
    pageSize: 8,
    page: 2,
  }

  return (
    <PageContainer>
      <EditableProTable<DataSourceType>
        rowKey="user_id"
        headerTitle="用户表格"
        // maxLength={5}
        scroll={{
          x: 960,
        }}
        recordCreatorProps={
          position !== 'hidden'
            ? {
                position: position as 'top',
                record: () => ({ user_id: 'add' }),
              }
            : false
        }
        loading={false}
        toolBarRender={() => [
          <ProFormRadio.Group
            key="render"
            fieldProps={{
              value: position,
              onChange: (e) => {
                console.log(position);
                setPosition(e.target.value)
              },
            }}
            options={[
              {
                label: '添加到顶部',
                value: 'top',
              },
              {
                label: '添加到底部',
                value: 'bottom',
              },
              {
                label: '隐藏',
                value: 'hidden',
              },
            ]}
          />,
        ]}
        columns={columns}
        params={params}
        request={async (
          params: T & {
            pageSize: number;
            current: number;
          },
        ) => {
          console.log(params);
          const msg = await selectUser({
            page: params.page,
            pageSize: params.pageSize,
          });
          return {
            data: msg.data,
            success: true,
            // total: 4,
          } 
        }}
        value={dataSource}
        onChange={setDataSource}
        pagination={{
          pageSize: 4,
          onChange: (page) => console.log(page),
        }}
        editable={{
          type: 'multiple',
          editableKeys,
          onSave: async (rowKey, data, row) => {
            console.log(rowKey, data, row); //请求接口
            const access = data.role_id === 1 ? 'admin' : 'user';
            if (rowKey === 'add') {
              const body = {
                code: 0,
                msg: 'insert',
                data: {
                  role_id: data.role_id,
                  access: access,
                  username: data.username,
                  password: 'aaaaaa',
                },
              };
              const { msg } = await addUser(body);
              if (msg === 'success') {
                message.success('添加成功');
              } else {
                message.error(msg);
              }
              
            } else {
              const body = {
                code: 2,
                msg: 'update',
                data: {
                  user_id: data.user_id,
                  role_id: data.role_id,
                  access: data.access,
                }
              }
              const { msg } = await editUser(body);
              if (msg === 'success') {
                message.success('更新成功');
              } else {
                message.error('更新错误')
              }
              
            }
            await waitTime(1000);
          },
          onChange: setEditableRowKeys,
        }}
      />
      {/* <ProCard title="表格数据" headerBordered collapsible defaultCollapsed>
        <ProFormField
          ignoreFormItem
          fieldProps={{
            style: {
              width: '100%',
            },
          }}
          mode="read"
          valueType="jsonCode"
          text={JSON.stringify(dataSource)}
        />
      </ProCard> */}
    </PageContainer>
  );
};